﻿using System;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Lightray.Hattrick.ChppLib
{
    [ComVisible(true)]
    public class BrowserWindow : Form
    {
        private WebBrowser _webBrowser;
        private GadgetInterface _gadgetInterface;
        private object _gadgetWindow;
        
        // TODO: must delay until web control is finished loading
        public BrowserWindow(GadgetInterface gadgetInterface, object gadgetWindow)
        {
            WindowState = FormWindowState.Minimized;
            _gadgetInterface = gadgetInterface;
            _gadgetWindow = gadgetWindow;
            startMessageThread();            
        }

        private void startMessageThread()
        {
            Thread messageLoopThread = new Thread(() => Application.Run(this));
            messageLoopThread.SetApartmentState(ApartmentState.STA);
            messageLoopThread.Start();
        }

        private void initControls()
        {
            Width = 400;
            Height = 400;
            ShowInTaskbar = false;
            FormBorderStyle = FormBorderStyle.FixedToolWindow;
            
            _webBrowser = new WebBrowser();
            _webBrowser.ObjectForScripting = _gadgetWindow;
            _webBrowser.Dock = DockStyle.Fill;
            _webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(_webBrowser_DocumentCompleted);
            Controls.Add(_webBrowser);
        }

        private void _webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            Height = _webBrowser.Document.Body.ScrollRectangle.Height + _webBrowser.Margin.Vertical + 50;
            Width = _webBrowser.Document.Body.ScrollRectangle.Width + _webBrowser.Margin.Horizontal + 50;
            WindowState = FormWindowState.Normal;
        }
     
        protected override void OnLoad(EventArgs e)
        {
            initControls();
        }

        public string File { set { _webBrowser.Navigate(value); } }        
    }
}
